const errorTypes = require('./error-types')
const wrapper = require('../wrapper')

const errorHandler = (error, ctx) => {
  let status, message

  switch (error.message) {
    case errorTypes.NICKNAME_OR_PASSWORD_IS_REQUIRED:
      status = 400  // Bad Request -> 参数有问题
      message = "用户名或密码不能为空~"
      break
    case errorTypes.USER_ALREADY_EXISTS:
      status = 409  // Conflict -> 参数冲突
      message = "该用户已注册~"
      break
    case errorTypes.USER_DOES_NOT_EXISTS:
      status = 409  // Conflict -> 参数冲突
      message = "用户不存在~"
      break
    case errorTypes.PASSWORD_IS_INCORRENT:
      status = 409  // Conflict -> 参数冲突
      message = "密码错误~"
      break
    case errorTypes.UN_AUTHORIZED:
      status = 401  // Bad Request -> 参数冲突/错误
      message = "无效的token"
      break
    case errorTypes.BAD_REQUEST:
      status = 500  // Conflict -> 参数冲突
      message = "服务器繁忙, 请稍后再试~"
      break
    default:
      status = 404
      message = "NOT FOUND"
  }

  ctx.status = status
  ctx.body = wrapper.wrapTo500(null, message)
}

module.exports = errorHandler
